//
//  AUEssenceTopicCell.swift
//  Alamofire
//
//  Created by Miss_Special on 2018/4/17.
//

import UIKit
import AwesomeUBaseModule
import Kingfisher
import SnapKit

class AUEssenceTopicCell: UITableViewCell {
    
    // bundle
    fileprivate var bundle: Bundle {
        get {
            return Bundle.init(for: type(of: self))
        }
    }
    
    // header
    fileprivate lazy var headerView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    fileprivate lazy var header_userIcon_imageView: UIImageView = {
        if let image = AUHomeModule.imageFromBundle(bundle: self.bundle, imageName: "defaultUserIcon@2x") {
            let imageView = UIImageView(image: image)
            imageView.layer.cornerRadius = 25 * au_kScreenScale
            imageView.layer.masksToBounds = true
            return imageView
        }
        return UIImageView()
    }()
    
    fileprivate lazy var header_nickname_label: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.font = UIFont.au_scaledFont(size: 14)
        label.textColor = common_textColor_blue
        return label
    }()
    
    fileprivate lazy var header_detail_label: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.font = UIFont.au_scaledFont(size: 12)
        label.textColor = common_textColor_gray
        return label
    }()
    
    fileprivate lazy var content_label: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.font = UIFont.au_scaledFont(size: 16)
        label.numberOfLines = 0
        label.textColor = common_textColor_black
        return label
    }()
    
    fileprivate lazy var contentImage_view: AUEssenceTopicPictureView = {
        let view = AUEssenceTopicPictureView.pictureView()
        view.isHidden = true
        return view
    }()
    
    fileprivate lazy var toolbar_view: AUEssenceTopicToolbar = {
        let view = AUEssenceTopicToolbar()
        return view
    }()
    
    fileprivate lazy var comment_view: AUEssenceTopicCommentView = {
        let commentView = AUEssenceTopicCommentView()
        return commentView
    }()
    
    fileprivate lazy var separatorLine_view: UIView = {
        let view = UIView()
        view.backgroundColor = common_backgroundColor_gray
        return view
    }()
    
    fileprivate var imageHeight_constraint: Constraint?
    fileprivate var commentHeight_constraint: Constraint?
    
    /// 数据模型
    var model: AUEssenceTopicModel? {
        didSet {
            guard let model = model else {
                return
            }
            
            // 处理header
            if let url = URL(string: model.user.header.first ?? "") {
                header_userIcon_imageView.kf.setImage(
                    with: url,
                    placeholder: AUHomeModule.imageFromBundle(bundle: self.bundle, imageName: "defaultUserIcon@2x"),
                    options: nil,
                    progressBlock: nil,
                    completionHandler: nil
                )
            }
            header_nickname_label.text = model.user.name
            header_detail_label.text = model.passtime
            
            // 文字内容
            let paragraphStyle = NSMutableParagraphStyle()
            //将行间距设置为28
            paragraphStyle.lineSpacing = 8
            //样式属性集合
            let attributes = [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16),
                              NSAttributedStringKey.paragraphStyle: paragraphStyle]
            content_label.attributedText = NSAttributedString(string: model.text, attributes: attributes)
            
            switch model.topicType {
                // 图片
            case .picture:
                if model.type == "gif" {
                    // gif图片
                    if model.picture_gif.gif_thumbnail.count > 0 && model.picture_gif.height > 0 {
                        contentImage_view.isHidden = false
                        contentImage_view.picture_gif = model.picture_gif
                        let pictureHeight = model.picture_gif.height / model.picture_gif.width * (au_kScreenWidth - 24 * au_kScreenScale)
                        imageHeight_constraint?.update(offset: pictureHeight > 1000 ? au_bigImageRemainingHeight : pictureHeight + 10)
                    }
                } else {
                    // 普通图片
                    if model.picture.thumbnail_small.count > 0 && model.picture.height > 0 {
                        contentImage_view.isHidden = false
                        contentImage_view.picture = model.picture
                        let pictureHeight = model.picture.height / model.picture.width * (au_kScreenWidth - 24 * au_kScreenScale)
                        imageHeight_constraint?.update(offset: pictureHeight > 1000 ? au_bigImageRemainingHeight : pictureHeight + 10)
                    }
                }
                
            case .video:
                if model.video.thumbnail.count > 0 && model.video.height > 0 {
                    contentImage_view.isHidden = false
                    contentImage_view.video = model.video
                    let videoHeight = model.video.height / model.video.width * (au_kScreenWidth - 24 * au_kScreenScale)
                    imageHeight_constraint?.update(offset: videoHeight + 10)
                }
            default:
                contentImage_view.isHidden = true
                imageHeight_constraint?.update(offset: 0)
            }
            
            // 评论内容
            comment_view.comments = model.top_comments
            let height = model.top_comments.reduce(0, { $0 + $1.cellHeight})
            commentHeight_constraint?.update(offset: height == 0 ? 0 : height + 10)
        }
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = UIColor.white
        
        // header
        contentView.addSubview(headerView)
        headerView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(74 * au_kScreenScale)
        }
        
        headerView.addSubview(header_userIcon_imageView)
        header_userIcon_imageView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 50 * au_kScreenScale, height: 50 * au_kScreenScale))
            make.left.equalTo(12 * au_kScreenScale)
            make.centerY.equalToSuperview()
        }
        
        headerView.addSubview(header_nickname_label)
        header_nickname_label.snp.makeConstraints { (make) in
            make.left.equalTo(header_userIcon_imageView.snp.right).offset(8 * au_kScreenScale)
            make.top.equalTo(header_userIcon_imageView).offset(3)
            make.right.equalToSuperview().offset(-12 * au_kScreenScale)
        }

        headerView.addSubview(header_detail_label)
        header_detail_label.snp.makeConstraints { (make) in
            make.left.equalTo(header_nickname_label)
            make.bottom.equalTo(header_userIcon_imageView).offset(-3)
            make.right.equalToSuperview().offset(-12 * au_kScreenScale)
        }
        
        // content_text
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalTo(12 * au_kScreenScale)
            make.top.equalTo(headerView.snp.bottom).offset(3)
            make.right.equalToSuperview().offset(-12 * au_kScreenScale)
        }
        
        // content_image
        contentView.addSubview(contentImage_view)
        contentImage_view.snp.makeConstraints { (make) in
            make.top.equalTo(content_label.snp.bottom)
            make.left.equalTo(12 * au_kScreenScale)
            make.right.equalToSuperview().offset(-12 * au_kScreenScale)
            imageHeight_constraint = make.height.equalTo(0).constraint
        }
        
        // toolbar
        contentView.addSubview(toolbar_view)
        toolbar_view.snp.makeConstraints { (make) in
            make.top.equalTo(contentImage_view.snp.bottom).priority(ConstraintPriority.high)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        // comment
        contentView.addSubview(comment_view)
        comment_view.snp.makeConstraints { (make) in
            make.top.equalTo(toolbar_view.snp.bottom)
            make.left.equalToSuperview().offset(12 * au_kScreenScale)
            make.right.equalToSuperview().offset(-12 * au_kScreenScale)
            make.bottom.equalTo(0)
            commentHeight_constraint = make.height.equalTo(0).constraint
        }
        
        // separatorLine
        contentView.addSubview(separatorLine_view)
        separatorLine_view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension AUEssenceTopicCell: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return model?.top_comments.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "AUEssenceTopicCommentCell", for: indexPath) as! AUEssenceTopicCommentCell
        
        if model!.top_comments.count > 0 {
            cell.commentModel = model?.top_comments[indexPath.row]
        }
        
        return cell
    }
}

extension AUEssenceTopicCell: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let contentModel = model, contentModel.top_comments.count > 0 else {
            return 0
        }
        return contentModel.top_comments[indexPath.row].cellHeight
    }
}
